# 用户账户相关功能
import datetime
import uuid

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
#
from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm


# 注册
def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'web/register.html', {'form': form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过后，存入数据库
        instance = form.save()  # 将数据写入数据库,会自动去除数据库中没有字段的数据
        policy_object = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        # 创建交易记录
        models.Transaction.objects.create(status=2, order=str(uuid.uuid4()), user=instance, price_policy=policy_object, count=0, price=0, start_datetime=datetime.datetime.now())
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


# 发送短信
def send_sms(request):
    form = SendSmsForm(request, data=request.GET)
    # 校验手机号不能为空和格式正确
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


# 短信登录
def login_sms(request):
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'web/login_sms.html', {'form': form})
    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 登录成功
        user_object = form.cleaned_data.get('mobile_phone')
        # 用户信息写入session
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


# 登录
def login(request):
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        from django.db.models import Q
        user_object = models.UserInfo.objects.filter(
            Q(email=username) | Q(username=username) | Q(mobile_phone=username)).filter(password=password).first()
        if user_object:
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('web:index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'web/login.html', {'form': form})


# 生成图片验证码
def image_code(request):
    from io import BytesIO
    from utils.image_code import check_code
    image_object, code = check_code()
    # 将验证码写入session
    request.session['image_code'] = code
    request.session.set_expiry(60)  # 设置session过期时间60s
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('web:index')
